package by.qizer.supercamp.dao;

import by.qizer.supercamp.domain.Owner;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Pribytkoyski Alexey
 *         User: qizer
 *         Date: 04.04.12
 */

@Repository
public class OwnerDAOImpl implements OwnerDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addOwner(Owner owner) {
        if (checkOwner(owner)) {
            sessionFactory.getCurrentSession().save(owner);
        }
    }

    @SuppressWarnings("unchecked")
    public List<Owner> listOwners() {
        return sessionFactory.getCurrentSession().createQuery("from Owner").list();
    }

    public void removeOwner(Integer id) {
        Owner owner = (Owner) sessionFactory.getCurrentSession().load(Owner.class, id);
        if (null != owner) {
            sessionFactory.getCurrentSession().delete(owner);
        }
    }


    private Boolean checkOwner(Owner owner) {
        String lastName = owner.getLastName();
        String firstName = owner.getFirstName();
        String phone = owner.getPhone().trim();

        if (phone.length() < 7) {
            return false;
        } else {
            int lengthPhone = phone.length();
            phone = phone.substring(lengthPhone - 7, lengthPhone);
        }

        String hql = "from Owner where lastName='" + lastName + "'" +
                "and firstName='" + firstName + "'" +
                "and phone like '%" + phone + "'";

        List<Owner> answer = sessionFactory.getCurrentSession().createQuery(hql).list();

        if (answer.isEmpty()) {
            return true;
        }

        return false;
    }
}
